﻿using Blm.Utils.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Utility;

namespace VisionCloud.Web
{
    public class UnzipTaskDataFileSystemMananger
    {
        internal static List<FileInfo> GetNeedToHandleFile_OldVersion(string taskDataRoot)
        {
            return GetNeedToHandleFileBase(taskDataRoot);
        }

        internal static List<FileInfo> GetNeedToHandleFile_NewVersion(string taskDataRoot)
        {
            var dirPath = Path.Combine(taskDataRoot, "DataFile");
            return GetNeedToHandleFileBase(dirPath);
        }

        internal static List<FileInfo> GetNeedToHandleFileBase(string dirPath)
        {
            try
            {
                List<FileInfo> listFile = new List<FileInfo>();
                var files = Directory.GetFiles(dirPath, "*.zip");
                if (files.Length <= 0)
                    return listFile;
                foreach (var file in files)
                {
                    if (!FileInfoUtil.IsFileInUse(file))
                    {
                        listFile.Add(new FileInfo(file));
                    }
                }
                return listFile;
            }
            catch (Exception ex)
            {
                Logger.Warn("GetNeedToHandleFileBase-：", ex);
                return new List<FileInfo>();
            }
        }

        internal static (string destDir, string deviceNo, string[] dir) DirectoryHandle(string srcFileFullName, string taskReportData, string taskData, string taskDataBackup)
        {
            Logger.Info($"开始处理文件:{srcFileFullName}");

            #region 解压

            string srcFileName = Path.GetFileNameWithoutExtension(srcFileFullName);
            int firstPositionNum = srcFileName.IndexOf("-");
            string deviceNo = srcFileName.Substring(0, firstPositionNum);
            string taskId = srcFileName.Substring(firstPositionNum + 1, 36);
            string uploadGuid = srcFileName.Substring(firstPositionNum + 1 + 36 + 1, 36);
            string destDirPath = Path.Combine(taskReportData, deviceNo, taskId, uploadGuid);
            if (!Directory.Exists(destDirPath))
            {
                Directory.CreateDirectory(destDirPath);
            }

            #region 解压文件

            string extractMessage = FileInfoUtil.ExtractToDirectory(srcFileFullName, destDirPath);
            if (!string.IsNullOrWhiteSpace(extractMessage))
            {
                string errorFolder = Path.Combine(taskData, "error");
                if (!Directory.Exists(errorFolder))
                {
                    Directory.CreateDirectory(errorFolder);
                }
                var zipFile = new FileInfo(srcFileFullName);
                // 将解压出错文件移动到erro文件夹中
                string errorPath = Path.Combine(errorFolder, zipFile.Name);
                // 错误文件已存在将其删除
                FileInfoUtil.DeleteFile(errorPath);
                File.Move(srcFileFullName, errorPath);
            }

            #endregion 解压文件

            #endregion 解压

            #region 移动到备份文件夹，后面下载使用

            try
            {
                //string backupFileName = Path.Combine(taskDataBackup, Path.GetFileName(file));
                //$"{deviceNo}-{taskId}_{uploadGuid}.zip"
                string backupDir = Path.Combine(taskDataBackup, deviceNo, taskId);
                string backupFileName = Path.Combine(backupDir, uploadGuid + ".zip");
                if (!Directory.Exists(backupDir))
                {
                    Directory.CreateDirectory(backupDir);
                }
                if (File.Exists(backupFileName))
                {
                    File.Delete(backupFileName);
                }
                File.Move(srcFileFullName, backupFileName);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
            }

            #endregion 移动到备份文件夹，后面下载使用

            var dir = Directory.GetDirectories(destDirPath);//只有一个项目名称的文件夹
            return (destDirPath, deviceNo, dir);
        }

        internal static void ErrorBuckUp(string taskData, string srcFileFullName)
        {
            string errorFolder = Path.Combine(taskData, "error");
            if (!Directory.Exists(errorFolder))
            {
                Directory.CreateDirectory(errorFolder);
            }

            if (!File.Exists(srcFileFullName))
            {
                return;
            }
            var zipFile = new FileInfo(srcFileFullName);
            // 将解压出错文件移动到erro文件夹中
            string errorPath = Path.Combine(errorFolder, zipFile.Name);
            // 错误文件已存在将其删除
            FileInfoUtil.DeleteFile(errorPath);
            File.Move(srcFileFullName, errorPath);
        }

        internal static string[] DirectoryHandle(UnzipTaskDataEntity entity, string taskReportData, string taskData, string taskDataBackup)
        {
            string srcFileFullName = entity.SrcFileInfo.FullName;
            Logger.Info($"开始处理文件:{srcFileFullName}");
            string[] result = Array.Empty<string>();
            try
            {
                if (entity.IsHaveError)
                {
                    ErrorBuckUp(taskData, srcFileFullName);
                    return result;
                }
                string srcFileName = Path.GetFileNameWithoutExtension(srcFileFullName);
                string destDirPath = entity.DestDirPath;// Path.Combine(taskReportData, deviceNo, taskId, uploadGuid);
                if (!Directory.Exists(destDirPath))
                {
                    Directory.CreateDirectory(destDirPath);
                }
                string extractMessage = Blm.VisionCloud.FrameWork.Utility.FileInfoUtil.ExtractToDirectory(srcFileFullName, destDirPath, true);
                if (!string.IsNullOrWhiteSpace(extractMessage))
                {
                    entity.IsHaveError = true;
                    entity.ErrorMessage = extractMessage;
                    ErrorBuckUp(taskData, srcFileFullName);
                    Logger.Error(extractMessage);
                    return result;
                }
                else
                {
                    if (!Directory.Exists(Path.GetDirectoryName(entity.backupFileName)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(entity.backupFileName));
                    }
                    if (File.Exists(entity.backupFileName))
                    {
                        File.Delete(entity.backupFileName);
                    }
                    File.Move(srcFileFullName, entity.backupFileName);
                    result = Directory.GetDirectories(destDirPath);//只有一个项目名称的文件夹
                    return result;
                }
            }
            catch (Exception e)
            {
                entity.IsHaveError = true;
                entity.ErrorMessage = e.ToString();
                ErrorBuckUp(taskData, srcFileFullName);
                Logger.Error(e.Message, e);
                return result;
            }
        }
    }
}